// 日志管理器 - 统一的日志和错误处理
export class Logger {
  constructor() {
    this.logs = []
    this.maxLogs = 1000
    this.logLevel = 'info' // debug, info, warn, error
  }

  setLevel(level) {
    this.logLevel = level
  }

  debug(message, data = null) {
    this._log('debug', message, data)
  }

  info(message, data = null) {
    this._log('info', message, data)
  }

  warn(message, data = null) {
    this._log('warn', message, data)
  }

  error(message, error = null) {
    this._log('error', message, error)
  }

  _log(level, message, data) {
    const levels = ['debug', 'info', 'warn', 'error']
    const currentLevelIndex = levels.indexOf(this.logLevel)
    const messageLevelIndex = levels.indexOf(level)

    if (messageLevelIndex < currentLevelIndex) {
      return
    }

    const logEntry = {
      timestamp: new Date().toISOString(),
      level,
      message,
      data
    }

    this.logs.push(logEntry)

    // 限制日志数量
    if (this.logs.length > this.maxLogs) {
      this.logs.shift()
    }

    // 输出到控制台
    const consoleMethod = console[level] || console.log
    if (data) {
      consoleMethod(`[${level.toUpperCase()}] ${message}`, data)
    } else {
      consoleMethod(`[${level.toUpperCase()}] ${message}`)
    }
  }

  getLogs(level = null) {
    if (level) {
      return this.logs.filter(log => log.level === level)
    }
    return [...this.logs]
  }

  clearLogs() {
    this.logs = []
  }

  exportLogs() {
    return JSON.stringify(this.logs, null, 2)
  }
}

// 错误边界处理
export class ErrorHandler {
  constructor(logger) {
    this.logger = logger
    this.setupGlobalErrorHandling()
  }

  setupGlobalErrorHandling() {
    // 捕获未处理的Promise拒绝
    window.addEventListener('unhandledrejection', (event) => {
      this.logger.error('未处理的Promise拒绝', {
        reason: event.reason,
        promise: event.promise
      })
      event.preventDefault()
    })

    // 捕获全局错误
    window.addEventListener('error', (event) => {
      this.logger.error('全局错误', {
        message: event.message,
        filename: event.filename,
        lineno: event.lineno,
        colno: event.colno,
        error: event.error
      })
    })
  }

  // 包装异步函数以捕获错误
  static wrapAsync(fn, errorHandler) {
    return async (...args) => {
      try {
        return await fn(...args)
      } catch (error) {
        if (errorHandler) {
          errorHandler(error)
        } else {
          console.error('异步函数执行失败:', error)
        }
        throw error
      }
    }
  }

  // 包装同步函数以捕获错误
  static wrap(fn, errorHandler) {
    return (...args) => {
      try {
        return fn(...args)
      } catch (error) {
        if (errorHandler) {
          errorHandler(error)
        } else {
          console.error('函数执行失败:', error)
        }
        throw error
      }
    }
  }
}

// 创建全局实例
export const logger = new Logger()
export const errorHandler = new ErrorHandler(logger)